/**
 * rollup常用插件 https://juejin.cn/post/7214350677539733564
 */
import path from 'node:path'
import fs from 'node:fs'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import postcss from 'rollup-plugin-postcss'
import babel from 'rollup-plugin-babel'
import { terser } from 'rollup-plugin-terser'
import { createFilter } from 'rollup-pluginutils'
import autoprefixer from 'autoprefixer'
import eslint from '@rollup/plugin-eslint'
// https://www.npmjs.com/package/rollup-plugin-copy
import copy from 'rollup-plugin-copy'
import eslintConfig from './eslint.config.js'

const exportString = (opts = {}) => {
    if (!opts.include) {
        throw Error('include option should be specified')
    }
    const filter = createFilter(opts.include, opts.exclude)
    return {
        name: 'exportString',
        transform(code, id) {
            if (filter(id)) {
                return {
                    code: `export default ${JSON.stringify(code)}`,
                    map: { mappings: '' }
                }
            }
        }
    }
}

const getInputs = (...args) => {
    const rc = {}
    const fn = (dir, parentName = []) => {
        fs.readdirSync(dir).forEach((item) => {
            const currPath = path.join(dir, item)
            const stat = fs.statSync(currPath)
            // console.log({ stat, item, parentName })
            if (stat.isDirectory()) {
                fn(currPath, [...parentName, item])
            } else {
                if (/\.js/.test(item) && !/.test/.test(item)) {
                    const name = [
                        ...parentName,
                        item.split('.')[0]
                    ].filter(Boolean).join('/')
                    rc[name] = currPath
                }
            }
        })
    }
    fn(...args, [])
    return rc
}

console.log(process.cwd())
const componentDir = path.resolve(process.cwd(), 'src')

const components = getInputs(componentDir)
console.log(components)

const defaultInputs = {
    input: {
        ...components
    },
    output: {
        dir: 'dist',
        chunkFileNames: '[name].js',
        format: 'es',
    },
    plugins: [
        eslint({
            include: ['components/**/*.js'],
            exclude: ['node_modules/**'],
            formatter: 'compact',
            overrideConfig: eslintConfig
        }),
        postcss({
            // minimize: true,
            inject: false,
            use: ['less'],
            extensions: ['css', 'less'],
            plugins: [
                autoprefixer()
            ]
        }),
        nodeResolve({
            extensions: ['.js']
        }),
        exportString({
            // 这将会处理所有的.svg文件
            include: [
                '**/*.svg'
            ]
        }),
        babel({
            exclude: 'node_modules/**',
            extensions: ['.js']
        }),
        // terser(),
        copy({
            targets: [{
                src: 'src/style.css',
                dest: 'dist'
            }]
        })
    ],
    watch: {
        clearScreen: false
    }
}

const inputsConfig = Object.keys(components).map((key) => {
    return {
        input: {
            [key]: components[key]
        },
        output: {
            dir: 'dist',
            chunkFileNames: '[name].js',
            format: 'es',
        },
        plugins: [
            eslint({
                include: ['components/**/*.js'],
                exclude: ['node_modules/**'],
                formatter: 'compact',
                overrideConfig: eslintConfig
            }),
            postcss({
                // minimize: true,
                // extract: true,
                use: ['less'],
                extensions: ['css', 'less'],
                plugins: [
                    autoprefixer()
                ]
            }),
            nodeResolve({
                extensions: ['.js']
            }),
            exportString({
                // 这将会处理所有的.svg文件
                include: [
                    '**/*.svg'
                ]
            }),
            babel({
                exclude: 'node_modules/**',
                extensions: ['.js']
            }),
            // terser(),
            copy({
                targets: [{
                    src: 'src/style.css',
                    dest: 'dist'
                }]
            })
        ],
        watch: {
            clearScreen: false
        }
    }
})

export default [
    // ...inputsConfig
    defaultInputs
]
